import { Component, OnInit } from '@angular/core';
import { MessageUtilsService } from '../../shared/services/message-utils.service';
import { Message } from 'primeng/api';
import { ProjectService } from '../service/project.service';
import * as _ from 'lodash';
import { Router } from '@angular/router';
import { CRUD_MODE } from '../../shared/config/app-settings';
import { UserService } from '../../shared/services/user.service';
declare var google: any;
@Component({
    selector: 'app-mapview',
    templateUrl: './mapview.component.html',
    styleUrls: ['./mapview.component.scss']
})
export class MapviewComponent implements OnInit {
    options: any;

    overlays: any[] = [];

    dialogVisible: boolean;

    markerTitle: string;

    selectedPosition: any;

    infoWindow: any;

    draggable: boolean;


    msgs: Message[] = [];

    projects: any[];
    user: any;

    constructor(private messageUtilsService: MessageUtilsService,
        private projectService: ProjectService,
        private userService: UserService,
        private router: Router
    ) { }

    ngOnInit() {
        //-33.8345824,151.0422507
        this.options = {
            center: { lat: -33.8345824, lng: 151.0422507 },
            zoom: 12
        };


        this.getCurrentUser();
        this.loadAllProject()
    }


    loadAllProject() {
        this.projectService.getAllPropertyLists().subscribe(res => {
            this.projects =  _.filter(res, (project)=>project['status'] !== 'inactive');
            // this.projects = res;
            this.initOverlays(this.projects);
            this.infoWindow = new google.maps.InfoWindow();
        });
    }

    getProjectInfo(_id) {
        // let item = this.projects[index];
        let item = _.find(this.projects, {id: _id});
        console.log("google map point click {}", item);
        let itemURL = `/shared/project-detail/${item.id}?mode=view`
        if (this.user) {
            itemURL = "/" + this.user.role + itemURL
        }
        return `
                    <div class="ui-g" style="width: 350px;">
                         <div class="ui-g-4">
                          <a href="${itemURL}">
                            <img class="card-img-top" style="width: 100px ;height: 80px;" src="${this.projectService.getLogo(item)}" alt="Card image cap">
                          </a>
                         </div>
                         <div class="ui-g-8">
                          <h4 style="color:black">${item.name}</h4>
                          <small class="text-black-50">${this.projectService.getFullName(item)}</small>
                          
                         </div>

                    </div>
        
      `;

    }

    goToProjectDetail(project) {
        this.router.navigate(['/agent/shared/project-detail/' + project.id], { queryParams: { mode: CRUD_MODE.VIEW } });
    }

    getCurrentUser() {
        this.userService.getCurrentUser().subscribe((user) => {
            this.user = user;
        });
    }

    handleMapClick(event) {
        this.dialogVisible = true;
        this.selectedPosition = event.latLng;
    }

    handleOverlayClick(event) {
        this.msgs = [];
        let isMarker = event.overlay.getTitle != undefined;

        if (isMarker) {
            let title = event.overlay.getTitle();
            this.infoWindow.setContent(this.getProjectInfo(+title));
            this.infoWindow.open(event.map, event.overlay);
            event.map.setCenter(event.overlay.getPosition());
            this.messageUtilsService.showInfo(this.msgs,title);
        }
        else {
            this.messageUtilsService.showInfo(this.msgs,'');
        }
    }


    addMarker() {
        this.overlays.push(new google.maps.Marker({ position: { lat: this.selectedPosition.lat(), lng: this.selectedPosition.lng() }, title: this.markerTitle, draggable: this.draggable }));
        this.markerTitle = null;
        this.dialogVisible = false;
    }

    handleDragEnd(event) {
        this.msgs = [];
        this.msgs.push({ severity: 'info', summary: 'Marker Dragged', detail: event.overlay.getTitle() });
    }

    initOverlays(projects) {
        if (!this.overlays || !this.overlays.length) {

            this.overlays = [
                //   new google.maps.Marker({position: {lat: 36.879466, lng: 30.667648}, title:1}),
                //   new google.maps.Marker({position: {lat: 36.883707, lng: 30.689216}, title:2}),
                //   new google.maps.Marker({position: {lat: 36.885233, lng: 30.702323}, title:3}),
                //   new google.maps.Polygon({paths: [
                //       {lat: 36.9177, lng: 30.7854},{lat: 36.8851, lng: 30.7802},{lat: 36.8829, lng: 30.8111},{lat: 36.9177, lng: 30.8159}
                //   ], strokeOpacity: 0.5, strokeWeight: 1,fillColor: '#1976D2', fillOpacity: 0.35
                //   }),
                //   new google.maps.Circle({center: {lat: 36.90707, lng: 30.56533}, fillColor: '#1976D2', fillOpacity: 0.35, strokeWeight: 1, radius: 1500}),
                //   new google.maps.Polyline({path: [{lat: 36.86149, lng: 30.63743},{lat: 36.86341, lng: 30.72463}], geodesic: true, strokeColor: '#FF0000', strokeOpacity: 0.5, strokeWeight: 2})
            ];
            for (let index = 0; index < this.projects.length; index++) {
                let project = this.projects[index];
                console.log("location (x,y,id)",project.x, project.y, project.id);
                this.overlays.push(new google.maps.Marker(
                    { position: { lat: project.y, lng: project.x }, title: "" + project.id }
                ));
            }



        }
    }

    zoomIn(map) {
        map.setZoom(map.getZoom() + 1);
    }

    zoomOut(map) {
        map.setZoom(map.getZoom() - 1);
    }

    clear() {
        this.overlays = [];
    }

}
